<template>
	<view class="address-container">
		<!-- 表单内容 -->
		<view class="form-container">
			<view class="card">
				<!-- 收货人姓名 -->
				<view class="form-item">
					<view class="label">收货人姓名</view>
					<input class="input" type="text" v-model="formData.receive_name" placeholder="请输入收货人姓名" />
				</view>

				<!-- 手机号码 -->
				<view class="form-item">
					<view class="label">手机号码</view>
					<input class="input" type="number" v-model="formData.receive_phone" placeholder="请输入收货人的手机号码" />
				</view>

				<!-- 省份选择 -->
				<view class="form-item">
					<view class="label">省份</view>
					<view class="select-wrapper picker">
						<picker v-if="provinces.length > 0" :range="provinces" range-key="name"
							@change="onProvinceChange" @cancel="showProvincePicker = false" class="pkbox">
							<view class="select-value">{{provinceName || '请选择省份'}}</view>
						</picker>
						<view class="arrow-icon"> &gt;</view>
					</view>
				</view>

				<!-- 市区选择 -->
				<view class="form-item" v-if="provinceId">
					<view class="label">市区</view>
					<view class="select-wrapper picker">
						<picker class="pkbox" v-if="cities.length > 0" :range="cities" range-key="name"
							@change="onCityChange" @cancel="showCityPicker = false">
							<view class="select-value">{{cityName || '请选择市区'}}</view>
						</picker>
						<view class="arrow-icon"> &gt;</view>
					</view>
				</view>

				<!-- 地区选择 -->
				<view class="form-item" v-if="cityId">
					<view class="label">地区</view>
					<view class="select-wrapper picker">
						<picker class="pkbox" v-if="districts.length > 0" :range="districts" range-key="name"
							@change="onDistrictChange" @cancel="showDistrictPicker = false">
							<view class="select-value">{{districtName || '请选择地区'}}</view>
						</picker>
						<view class="arrow-icon"> &gt;</view>
					</view>
				</view>

				<!-- 默认地址 -->
				<view class="form-item switch-item">
					<view class="label">默认地址</view>
					<switch class="switch" :checked="formData.is_default === 1" @change="onDefaultChange"
						active-color="#e64340" />
				</view>

				<!-- 详细地址 -->
				<view class="form-item">
					<view class="label">详细地址</view>
					<textarea class="textarea" v-model="formData.address" placeholder="请输入街道门牌等信息" />
				</view>
			</view>
		</view>

		<!-- 保存按钮 -->
		<view class="save-btn" @click="saveAddress">{{isEdit ? '更新地址' : '保存地址'}}</view>

	</view>
</template>

<script>
	import {
		getFirstArea,
		getSencodeArea,
		getAddressInfo,
		addAddress,
		editAddress
	} from '../../api/request';

	export default {
		data() {
			return {
				isEdit: false, // 是否为编辑模式
				addressId: '', // 地址ID（编辑模式下有值）
				formData: {
					receive_name: '',
					receive_phone: '',
					region: [], // 地区ID数组 [provinceId, cityId, districtId]
					address: '',
					is_default: 0
				},
				// 地区数据
				provinces: [], // 省份列表
				cities: [], // 城市列表
				districts: [], // 地区列表
				provinceId: '', // 选中的省份ID
				provinceName: '', // 选中的省份名称
				cityId: '', // 选中的城市ID
				cityName: '', // 选中的城市名称
				districtId: '', // 选中的地区ID
				districtName: '', // 选中的地区名称
				// 选择器显示状态
				showProvincePicker: false,
				showCityPicker: false,
				showDistrictPicker: false
			};
		},
		onLoad(options) {
			// 初始化地区数据
			this.initRegionData();

			// 检查是否为编辑模式
			if (options && options.id) {
				this.isEdit = true;
				uni.setNavigationBarTitle({
					title: '编辑地址'
				})
				this.addressId = options.id;
				this.getAddressDetail();
				console.log('编辑模式:', this.isEdit);
			}
		},
		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack();
			},

			// 初始化地区数据
			initRegionData() {
				uni.showLoading({
					title: '加载中'
				});
				getFirstArea().then(res => {
					uni.hideLoading();
					if (res.code === 1 && res.data) {
						this.provinces = res.data.map(item => ({
							id: item.id,
							name: item.area_name,
							parent_id: item.parent_id,
							area_code: item.area_code,
						}));
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取省份数据失败', err);
					uni.showToast({
						title: '获取省份数据失败',
						icon: 'none'
					});
				});
			},

			// 获取地址详情（编辑模式）
			getAddressDetail() {
				uni.showLoading({
					title: '加载中'
				});
				getAddressInfo({
					address_id: this.addressId
				}).then(res => {
					uni.hideLoading();
					if (res.code === 1 && res.data) {
						const data = res.data;
						this.formData.receive_name = data.receive_name;
						this.formData.receive_phone = data.receive_phone;
						this.formData.address = data.address;
						this.formData.is_default = data.is_default;
						this.formData.region = data.region || [];

						// 设置地区信息
						if (this.formData.region.length >= 3) {
							this.provinceId = this.formData.region[0];
							this.cityId = this.formData.region[1];
							this.districtId = this.formData.region[2];
							this.provinceName = data.area_parent;
							this.cityName = data.area_son;
							this.districtName = data.area_grandson;

							// 加载城市和地区数据
							this.loadCities();
						} else {
							// 如果地区数据不完整，尝试加载省份数据
							this.loadCities();
						}
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取地址详情失败', err);
					uni.showToast({
						title: '获取地址详情失败',
						icon: 'none'
					});
				});
			},

			// 加载城市数据
			loadCities() {
				uni.showLoading({
					title: '加载中'
				});
				getSencodeArea({
					parent_id: this.provinceId
				}).then(res => {
					uni.hideLoading();
					// 保存当前cityId（编辑模式下）
					const currentCityId = this.isEdit ? this.cityId : '';
					console.log('currentCityId----------:', currentCityId);
					this.cities = [];
					// 非编辑模式下才重置城市名称
					if (!this.isEdit) {
						this.cityName = '';
						this.districts = [];
						this.districtId = '';
						this.districtName = '';
						this.formData.region = [this.provinceId];
					}

					if (res.code === 1 && res.data) {
						this.cities = res.data.map(item => ({
							id: item.id,
							name: item.area_name
						}));

						// 如果是编辑模式且有cityId，自动选中城市
						if (this.isEdit && currentCityId) {
							const cityIndex = this.cities.findIndex(item => item.id == currentCityId);
							if (cityIndex != -1) {
								this.cityId = currentCityId;
								this.cityName = this.cities[cityIndex].name;
								this.formData.region = [this.provinceId, currentCityId];
								console.log('编辑模式下选中城市:', this.cityName, 'ID:', this.cityId);
								// 加载地区数据
								this.loadDistricts();
							} else {
								// 如果找不到对应城市，重置cityId
								this.cityId = '';
								this.cityName = '';
								this.districts = [];
								this.districtId = '';
								this.districtName = '';
								this.formData.region = [this.provinceId];
								console.log('编辑模式下未找到对应城市，已重置');
							}
						} else if (this.cities.length > 0 && !this.isEdit) {
							// 非编辑模式下默认选中第一个城市
							this.cityId = this.cities[0].id;
							this.cityName = this.cities[0].name;
							this.formData.region = [this.provinceId, this.cityId];
							this.loadDistricts();
						}
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取城市数据失败', err);
					uni.showToast({
						title: '获取城市数据失败',
						icon: 'none'
					});
				});
			},

			// 加载地区数据
			loadDistricts() {
				uni.showLoading({
					title: '加载中'
				});
				// 保存当前districtId（编辑模式下）
				const currentDistrictId = this.isEdit ? this.districtId : '';
				getSencodeArea({
					parent_id: this.cityId
				}).then(res => {
					uni.hideLoading();
					this.districts = [];
					// 非编辑模式下才重置地区名称
					if (!this.isEdit) {
						this.districtName = '';
						this.formData.region = [this.provinceId, this.cityId];
					}

					if (res.code === 1 && res.data) {
						this.districts = res.data.map(item => ({
							id: item.id,
							name: item.area_name
						}));

						// 如果是编辑模式且有districtId，自动选中地区
						if (this.isEdit && currentDistrictId) {
							const districtIndex = this.districts.findIndex(item => item.id == currentDistrictId);
							if (districtIndex != -1) {
								this.districtId = currentDistrictId;
								this.districtName = this.districts[districtIndex].name;
								this.formData.region = [this.provinceId, this.cityId, currentDistrictId];
								console.log('编辑模式下选中地区:', this.districtName, 'ID:', this.districtId);
							} else {
								// 如果找不到对应地区，重置districtId
								this.districtId = '';
								this.districtName = '';
								this.formData.region = [this.provinceId, this.cityId];
								console.log('编辑模式下未找到对应地区，已重置');
							}
						} else if (this.districts.length > 0 && !this.isEdit) {
							// 非编辑模式下默认选中第一个地区
							this.districtId = this.districts[0].id;
							this.districtName = this.districts[0].name;
							this.formData.region = [this.provinceId, this.cityId, this.districtId];
						}
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取地区数据失败', err);
					uni.showToast({
						title: '获取地区数据失败',
						icon: 'none'
					});
				});
			},

			// 省份选择变化
			onProvinceChange(e) {
				const index = e.detail.value;
				const province = this.provinces[index];
				this.provinceId = province.id;
				this.provinceName = province.name;
				this.formData.region = [province.id];

				// 重置城市和地区
				this.cityId = '';
				this.cityName = '';
				this.districtId = '';
				this.districtName = '';
				this.cities = [];
				this.districts = [];

				// 加载城市数据
				this.loadCities();

				this.showProvincePicker = false;
			},

			// 城市选择变化
			onCityChange(e) {
				const index = e.detail.value;
				const city = this.cities[index];
				this.cityId = city.id;
				this.cityName = city.name;
				this.formData.region = [this.provinceId, this.cityId];
				this.districts = [];
				this.districtId = '';
				this.districtName = '';
				this.loadDistricts();
			},

			// 地区选择变化
			onDistrictChange(e) {
				const index = e.detail.value;
				const district = this.districts[index];
				this.districtId = district.id;
				this.districtName = district.name;
				this.formData.region = [this.provinceId, this.cityId, this.districtId];
			},

			// 默认地址开关变化
			onDefaultChange(e) {
				this.formData.is_default = e.detail.value ? 1 : 0;
			},

			// 验证表单
			validateForm() {
				if (!this.formData.receive_name.trim()) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return false;
				}

				if (!this.formData.receive_phone || !/^1[3-9]\d{9}$/.test(this.formData.receive_phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
					return false;
				}

				if (!this.provinceId || !this.cityId || !this.districtId) {
					uni.showToast({
						title: '请选择完整地区',
						icon: 'none'
					});
					return false;
				}

				if (!this.formData.address.trim()) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return false;
				}

				return true;
			},

			// 保存地址
			saveAddress() {
				// 验证表单
				if (!this.validateForm()) {
					return;
				}

				// 准备请求参数
				const params = {
					receive_name: this.formData.receive_name,
					receive_phone: this.formData.receive_phone,
					region: this.formData.region.join(','), // 转为逗号分隔的字符串
					address: this.formData.address,
					is_default: this.formData.is_default ? 1 : 0
				};

				// 如果是编辑模式，添加id参数
				if (this.isEdit) {
					params.id = this.addressId;
				}

				uni.showLoading({
					title: '处理中'
				});
				// 调用接口
				console.log(this.isEdit)
				const requestPromise = this.isEdit ? editAddress(params) : addAddress(params);
				console.log(requestPromise)

				requestPromise
					.then(res => {
						uni.hideLoading();
						if (res.code === 1) {
							uni.showToast({
								title: this.isEdit ? '更新成功' : '添加成功'
							});
							// 返回地址列表页
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.msg || (this.isEdit ? '更新失败' : '添加失败'),
								icon: 'none'
							});
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error(this.isEdit ? '更新地址失败' : '添加地址失败', err);
						uni.showToast({
							title: this.isEdit ? '更新地址失败' : '添加地址失败',
							icon: 'none'
						});
					});
			}
		}
	};
</script>

<style scoped lang="scss">
	.address-container {
		padding: 20rpx 0 120rpx;
		background-color: #f5f5f5;
	}

	/* 表单样式 */
	.form-container {
		padding: 0 30rpx;
	}

	.card {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		position: relative;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 30rpx;
		color: #333;
		width: 160rpx;
		font-weight: 500;
	}

	.input {
		flex: 1;
		font-size: 30rpx;
		color: #333;
		padding: 15rpx 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		transition: all 0.3s ease;
	}

	.input:focus {
		background-color: #fff;
		box-shadow: 0 0 0 2rpx #e64340;
		outline: none;
	}

	.pkbox {
		width: 100%;
		text-align: left;
	}

	.select-wrapper {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15rpx 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
	}

	.select-value {
		font-size: 30rpx;
		color: #666;
		// text-align: right;
		flex: 1;
	}

	.arrow-icon {
		width: 30rpx;
		height: 30rpx;
		margin-left: 10rpx;
		line-height: 30rpx;
		color: #666;
		// transition: transform 0.3s ease;
	}

	// .picker:active .arrow-icon {
	// 	transform: rotate(90deg);
	// }

	.switch-item {
		padding: 20rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.switch {
		transform: scale(1.2);
		transition: all 0.3s ease;
	}

	.textarea {
		flex: 1;
		font-size: 30rpx;
		color: #333;
		min-height: 180rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		transition: all 0.3s ease;
		resize: none;
	}

	.textarea:focus {
		background-color: #fff;
		box-shadow: 0 0 0 2rpx #e64340;
		outline: none;
	}

	/* 保存按钮 */
	.save-btn {
		position: fixed;
		bottom: 40rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 690rpx;
		height: 98rpx;
		background-color: #e64340;
		color: #fff;
		font-size: 34rpx;
		text-align: center;
		line-height: 98rpx;
		border-radius: 49rpx;
		box-shadow: 0 4rpx 20rpx rgba(230, 67, 64, 0.3);
		transition: all 0.3s ease;
		font-weight: 500;
	}

	.save-btn:active {
		background-color: #d43835;
		transform: translateX(-50%) scale(0.98);
		box-shadow: 0 2rpx 10rpx rgba(230, 67, 64, 0.2);
	}
</style>